package com.wontube.smr.web.controller.video;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.wontube.client.modle.vo.PagenateInfo;
import com.wontube.client.remote.Remoting;
import com.wontube.smr.client.model.po.Movie;
import com.wontube.smr.client.model.vo.AudioFiles;
import com.wontube.smr.client.model.vo.MVChartItems;
import com.wontube.smr.client.model.vo.MovieItems;
import com.wontube.smr.web.client.IMVWebHandler;
import com.wontube.smr.web.client.IMp3WebHandler;
import com.wontube.smr.web.client.model.bo.QueryItemParams;

/**
 * video -> music
 * 
 * @author tanggf(2012-4-14)
 * 
 */
@Controller("video-music")
public class MusicController {
	// 音乐排行榜参数
	private final static int CHART_PAGE_SIZE = 10;	

	// 音乐明细参数
	private final static int BROWSE_PAGE_SIZE = 40;	
	
	private final static int MP3_PAGE_SIZE = 50;
	
	@RequestMapping("/music")
	public void musicHome(HttpServletRequest request, 
			HttpServletResponse response) throws IOException{
		response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
		response.sendRedirect(request.getContextPath() + "/music/");		
	}

	/**
	 * video music 首页
	 * 
	 * @return
	 */
	@RequestMapping("/music/")
	public ModelAndView musicHome() {
		return browseMusicHome();
	}
	
	@RequestMapping("/music/video")
	public void v1(HttpServletRequest request, 
			HttpServletResponse response) throws IOException{
		response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
		response.sendRedirect(request.getContextPath() + "/music/video/");		
	}

	@RequestMapping("/music/video/")
	public ModelAndView browseMusicHome() {
		IMVWebHandler handler = getMvHandler();
		QueryItemParams params = new QueryItemParams();
		params.setNeedGenres(true);
		MovieItems items = handler.listVevoMusics(params, new PagenateInfo(1, BROWSE_PAGE_SIZE));
		ModelAndView mv = new ModelAndView("video/music/music_index");
		mv.addObject("musicItems", items);
		if(items != null){
			mv.addObject("genres", items.getGenres());
		}
		return mv;
	}
	
	@RequestMapping("/music/videos")
	public ModelAndView browses(){
		IMVWebHandler handler = getMvHandler();
		ModelAndView mv = new ModelAndView("video/music/music_index");
		mv.addObject("genres", handler.selectAllMusicGenres());
		return mv;
	}
	
	@RequestMapping("/music/video/query")
	public ModelAndView music_query(QueryItemParams params,
			@RequestParam(value = "page", required = false, defaultValue = "1") Integer page){
		IMVWebHandler handler = getMvHandler();		
		params.setNeedGenres(false);
		MovieItems items = handler.listVevoMusics(params, new PagenateInfo(page, BROWSE_PAGE_SIZE));
		ModelAndView mv = new ModelAndView("video/music/music_list");
		mv.addObject("musicItems", items);	
		return mv;
	}

	@RequestMapping("/music/video/{id}")
	public ModelAndView browse_music_detail(@PathVariable("id") String movieId, HttpServletResponse response)
			throws IOException {
		IMVWebHandler handler = getMvHandler();
		Movie movie = handler.getMV(movieId);
		if (movie == null) {
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			return null;
		} else {
			ModelAndView mv = new ModelAndView("video/music/detail/detail_index");
			mv.addObject("show", movie);			
			mv.addObject("genres", handler.selectAllMusicGenres());
			return mv;
		}
	}

	@RequestMapping("/music/video/watch-{id}")
	public ModelAndView browse_music_play(@PathVariable("id") String movieId, HttpServletResponse response)
			throws IOException {
		IMVWebHandler handler = getMvHandler();
		Movie movie = handler.getMV(movieId);
		if (movie == null) {
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			return null;
		} else {
			ModelAndView mv = new ModelAndView("video/music/play/music_player");
			mv.addObject("movie", movie);
			mv.addObject("genres", handler.selectAllMusicGenres());
			return mv;
		}
	}
	
	@RequestMapping("/music/video/relate/{id}")
	public ModelAndView browse_music_relate(@PathVariable("id") String movieId, HttpServletResponse response)
			throws IOException {
		IMVWebHandler handler = getMvHandler();		
		QueryItemParams params = new QueryItemParams();
		params.setNeedGenres(false);
		MovieItems items = handler.listVevoMusics(params, new PagenateInfo(1, 6));
		ModelAndView mv = new ModelAndView("video/music/play/music_relate");
		List<Movie> list = new ArrayList<Movie>();
		for (Movie movie : items.getItems()) {
			if (!movie.getId().equals(movieId) && list.size() < 5) {
				list.add(movie);
			}
		}
		items.setItems(list);
		mv.addObject("musicItems", list);	
		return mv;
	}
	
	@RequestMapping("/music/video/alpha/{alpha}")
	public ModelAndView browseMusicsByAlpha(@PathVariable("alpha") String initial) throws IOException {
		ModelAndView mv = getVevoMusicViewWithGenres(null, initial, null, null);
		mv.addObject("alpha",initial);
		return mv;
	}
	
	@RequestMapping("/music/video/popular/{popular}")
	public ModelAndView browse_music_popular(@PathVariable("popular") String popular) throws IOException {
		ModelAndView mv = getVevoMusicViewWithGenres(null, null, popular, null);
		mv.addObject("period",popular);
		return mv;
	}

	@RequestMapping("/music/video/genre/{genre}")
	public ModelAndView browse_music_genre(@PathVariable("genre") String genre) throws IOException {
		ModelAndView mv = getVevoMusicViewWithGenres(genre, null, null, null);
		mv.addObject("genre", genre);
		return mv;
	}
	
	private ModelAndView getVevoMusicViewWithGenres(String genre, String initial, String period, Integer page){
		if(page == null || page.intValue() < 1){
			page = 1;
		}
		
		QueryItemParams params = new QueryItemParams();
		params.setNeedGenres(true);
		params.setGenre(genre);
		params.setInitial(initial);
		params.setPeriod(period);
		
		IMVWebHandler handler = getMvHandler();
		MovieItems items = handler.listVevoMusics(params, new PagenateInfo(page, BROWSE_PAGE_SIZE));
		
		ModelAndView mv = new ModelAndView("video/music/music_index");
		mv.addObject("musicItems", items);
		if(items != null){
			mv.addObject("genres", items.getGenres());
		}
		return mv;
	}	
	
	/**
	 * 301
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/music/artist")
	public void v2(HttpServletRequest request, 
			HttpServletResponse response) throws IOException{
		response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
		response.sendRedirect(request.getContextPath() + "/music/artist/");		
	}

	@RequestMapping("/music/artist/")
	public ModelAndView artist_music() {
		ModelAndView mv = new ModelAndView("/video/music/artist/artist_index");
		IMVWebHandler handler = getMvHandler();		
		MVChartItems vevoCharts = handler.listVevoTopArtists(new PagenateInfo(1, BROWSE_PAGE_SIZE));
		mv.addObject("artistItems", vevoCharts);		
		return mv;		
	}
	
	@RequestMapping("/music/artists/query")
	public ModelAndView artist_music_query(@RequestParam(value = "page", required = false) Integer page) {
		ModelAndView mv = new ModelAndView("/video/music/artist/artist_list");
		IMVWebHandler handler = getMvHandler();		
		MVChartItems vevoCharts =  handler.listVevoTopArtists(new PagenateInfo(page, BROWSE_PAGE_SIZE));
		if (vevoCharts != null) {
			mv.addObject("artistItems", vevoCharts);					
		}
		return mv;
	}

	/**
	 * 某个artist的video 信息首页
	 * @param artist
	 * @return
	 */
	@RequestMapping("/music/artist/{artist}")
	public ModelAndView artist_music_list(@PathVariable("artist") String artist) {
		ModelAndView mv = new ModelAndView("video/music/artist/artist_music_index");		
		IMVWebHandler mvHandler = getMvHandler();
		MovieItems movies = mvHandler.selectMusicByArtist(artist, new PagenateInfo(1, BROWSE_PAGE_SIZE));
		mv.addObject("artistItems", movies);		
		mv.addObject("artist", artist);	
		return mv;
	}
	
	@RequestMapping("/music/artist/{artist}/{id}")
	public ModelAndView artist_music_detail(@PathVariable("id") String movieId, HttpServletResponse response)
			throws IOException {
		IMVWebHandler handler = getMvHandler();
		Movie movie = handler.getMV(movieId);
		if (movie == null) {
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			return null;
		} else {
			ModelAndView mv = new ModelAndView("video/music/detail/detail_index");
			mv.addObject("show", movie);		
			mv.addObject("artistDetail", true);
			return mv;
		}
	}
	
	/**
	 * 查询更多artist的video信息
	 * @param artist
	 * @param page
	 * @return
	 */
	@RequestMapping("/music/artist/list_musics")
	public ModelAndView listArtistMusics(
			@RequestParam("artist") String artist,
			@RequestParam(value="page", required=false, defaultValue="1") Integer page) {
		ModelAndView mv = new ModelAndView("video/music/artist/artist_music_list");		
		IMVWebHandler mvHandler = getMvHandler();
		MovieItems movies = mvHandler.selectMusicByArtist(artist, new PagenateInfo(page, BROWSE_PAGE_SIZE));
		mv.addObject("artistItems", movies);		
		mv.addObject("artist", artist);		
		return mv;
	}	

	@RequestMapping("/music/artist/watch-{id}")
	public ModelAndView artist_music_play(@PathVariable("id") String movieId, HttpServletResponse response)
			throws IOException {
		IMVWebHandler handler = getMvHandler();
		Movie movie = handler.getMV(movieId);
		if (movie == null) {
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			return null;
		} else {
			ModelAndView mv = new ModelAndView("video/music/play/music_player");
			mv.addObject("movie", movie);	
			mv.addObject("artistPlay", true);
			return mv;
		}
	}
	
	@RequestMapping("/music/chart")
	public void v3(HttpServletRequest request, 
			HttpServletResponse response) throws IOException{
		response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
		response.sendRedirect(request.getContextPath() + "/music/chart/");		
	}

	@RequestMapping("/music/chart/")
	public ModelAndView musicChart() {
		ModelAndView mv = new ModelAndView("/video/music/charts/charts_index");
		IMVWebHandler handler = getMvHandler();		
		//vevoArtists & vevoTops
		Map<String, MVChartItems> maps = handler.getVevoChartsHome(new PagenateInfo(1, CHART_PAGE_SIZE));
		mv.addAllObjects(maps);
		return mv;
	}
	
	@RequestMapping("/music/chart/video/{period}")
	public ModelAndView getVideoChart(@PathVariable("period") String period){
		ModelAndView mv = new ModelAndView("video/music/charts/video_list");
		IMVWebHandler handler = getMvHandler();		
		MVChartItems items = handler.getVevoVideoCharts(period, new PagenateInfo(1, CHART_PAGE_SIZE));
		mv.addObject("vevoTops", items);
		return mv;
	}
	
	@RequestMapping("/music/chart/artist/{period}")
	public ModelAndView getArtistChart(@PathVariable("period") String period){
		ModelAndView mv = new ModelAndView("video/music/charts/artist_list");
		IMVWebHandler handler = getMvHandler();		
		MVChartItems items = handler.getVevoArtistCharts(period, new PagenateInfo(1, CHART_PAGE_SIZE));
		mv.addObject("vevoArtists", items);
		return mv;
	}
	
	@RequestMapping("/music/mp3")
	public void v4(HttpServletRequest request, 
			HttpServletResponse response) throws IOException{
		response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
		response.sendRedirect(request.getContextPath() + "/music/mp3/");		
	}
	
	@RequestMapping("/music/mp3/")
	public ModelAndView music_mp3() {
		ModelAndView mv = new ModelAndView("/video/music/mp3/mp3_index");
		IMVWebHandler handler = getMvHandler();		
		//vevoMusics && vevoArtists
		Map<String, Object> maps = handler.getMp3Home();
		mv.addAllObjects(maps);
		return mv;
	}
	
	@RequestMapping("/music/list/{page}")
	public ModelAndView listMusics(@RequestParam(value="ajax", required=false) String ajax,
			@PathVariable("page") Integer page) {
		if(page.intValue() < 1){
			page = 1;
		}
		
		ModelAndView mv = new ModelAndView();
		IMVWebHandler handler = getMvHandler();		
		MovieItems musicItems = handler.listVevoMusics(new PagenateInfo(page, MP3_PAGE_SIZE));		
		mv.addObject("vevoMusics", musicItems);
		
		if(ajax != null){		
			mv.setViewName("/video/music/mp3/mp3_list");	
		}else{
			mv.setViewName("/video/music/mp3/mp3_index");		
			mv.addObject("page", page);
			mv.addObject("vevoArtists", handler.listVevoTopArtists(new PagenateInfo(1, 25)));
		}
		
		return mv;		
	}
	
	@RequestMapping("/music/search")
	public ModelAndView searchMp3(@RequestParam("query") String query, 
			@RequestParam(value="page", required=false, defaultValue="1") Integer page){
		ModelAndView mv = new ModelAndView("video/music/mp3/mp3_search_result");
		Remoting<IMp3WebHandler> remoting = new Remoting<IMp3WebHandler>();
		remoting.setReadTimeout(60000); // 查询较慢
		IMp3WebHandler handler = remoting.createService(IMp3WebHandler.class);
		AudioFiles files = handler.search(query, page);
		mv.addObject("audioFiles", files);
		mv.addObject("query", query);
		mv.addObject("page", page);
		return mv;
	}
	
	@RequestMapping("/music/{query}")
	public ModelAndView searchMusic(@PathVariable("query") String query){
		return musicMp3Query(query);
	}
	
	@RequestMapping("/music/{query}/{page}")
	public ModelAndView searchMusic2(@PathVariable("query") String query, @PathVariable("page") Integer page){
		return mp3Search(query, page);
	}

	@RequestMapping("/music/mp3/{query}")
	public ModelAndView musicMp3Query(@PathVariable("query") String query) {
		ModelAndView mv = mp3Search(query, 1);
		return mv;
	}

	@RequestMapping(value = "/music/mp3/{query}/{page}", method = RequestMethod.GET)
	public ModelAndView mp3Search(@PathVariable("query") String query, @PathVariable("page") Integer page) {
		Remoting<IMp3WebHandler> remoting = new Remoting<IMp3WebHandler>();
		remoting.setReadTimeout(60000); // 查询较慢
		IMp3WebHandler handler = remoting.createService(IMp3WebHandler.class);
		ModelAndView mv = new ModelAndView();
		mv.addObject("searchMusic", true);
		if (!"".equals(query)) {
			AudioFiles files = handler.search(query, page);
			mv.addObject("audioFiles", files);
			mv.setViewName("video/music/mp3/mp3_search_index");
		}
		mv.addObject("query", query);
		mv.addObject("page", page);
		//String upstreamUrl = remoting.getHeaders().get("who");
		//mv.addObject("serverUrl", upstreamUrl);

		return mv;
	}
	
	private IMVWebHandler getMvHandler() {
		Remoting<IMVWebHandler> remoting = new Remoting<IMVWebHandler>();
		return remoting.createService(IMVWebHandler.class);
	}	
	
	//====redirect 301=====
	@RequestMapping("/music/Call Me Maybe/")
	public void m1(HttpServletRequest request, 
			HttpServletResponse response) throws IOException{	
		response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
		response.sendRedirect(request.getContextPath() + "/music/Call Me Maybe");	
	}
	
	@RequestMapping("/music/Somebody That I Used To Know/")
	public void m2(HttpServletRequest request, 
			HttpServletResponse response) throws IOException{	
		response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
		response.sendRedirect(request.getContextPath() + "/music/Somebody That I Used To Know");	
	}
}
